package com.sau.pixelcart.controller;

import com.sau.pixelcart.common.exception.AccountException;
import com.sau.pixelcart.common.exception.BusinessException;
import com.sau.pixelcart.common.properties.JwtProperties;
import com.sau.pixelcart.common.result.PageResult;
import com.sau.pixelcart.common.result.Result;
import com.sau.pixelcart.common.utils.JwtUtil;
import com.sau.pixelcart.domain.dto.UserEmailDTO;
import com.sau.pixelcart.domain.dto.UserDTO;
import com.sau.pixelcart.domain.dto.UserPageDTO;
import com.sau.pixelcart.domain.dto.UserRoleDTO;
import com.sau.pixelcart.domain.entity.User;
import com.sau.pixelcart.domain.vo.UserRoleVO;
import com.sau.pixelcart.domain.vo.UserVO;
import com.sau.pixelcart.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户信息表 前端控制器
 * </p>
 *
 * @author Inton
 * @since 2025-03-08
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    private Result login(@RequestBody UserDTO userDTO){
        log.info("开始用户登录...{}",userDTO.getUsername());
        User user = userService.login(userDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getUserId());
        claims.put("role", user.getRole()); // 添加角色信息到载荷
        String token = "";
        //判断当前用户身份
        if (!user.getRole().isEmpty()) {
            token = JwtUtil.createJWT(
                    jwtProperties.getSecretKey(),
                    jwtProperties.getTtl(),
                    claims);
        }else{
            throw new AccountException("当前用户权限信息错误");
        }

        log.info("正在生成token...{}",token);

        //在数据库中记录登录时间
        userService.setLoginTime(user.getUserId());

        log.info("当前用户权限：{}",user.getRole());

        UserVO userVO = UserVO.builder()
                .userId(user.getUserId())
                .username(user.getUsername())
                .role(user.getRole()).build();

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("userInfo", userVO);

        return Result.success(resultMap);
    }

    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        log.info("用户注册...{}",userDTO.getUsername());
        User user = userService.register(userDTO);
        UserVO userVO = UserVO.builder()
                .userId(user.getUserId())
                .username(user.getUsername())
                .build();
        log.info("注册成功：{}",userVO);
        return Result.success(userVO);
    }

    /**
     * 修改密码
     * @param userDTO
     * @return
     */
    @PutMapping("/password")
    public Result changePassword(@RequestBody UserDTO userDTO){
        log.info("修改密码...");
        userService.changePassword(userDTO);
        return Result.success();
    }

    /**
     * 用户退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        log.info("退出登录...{}",jwtProperties.getTtl());
        return Result.success();
    }

    /**
     * 用户分页查询
     * @param userPageDTO
     * @return
     */
    @GetMapping("/list")
    public Result list(UserPageDTO userPageDTO){
        log.info("用户分页查询...");
        PageResult<UserVO> userVOPageResult = userService.pageQuery(userPageDTO);
        return Result.success(userVOPageResult);
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/delete/{userId}")
    public Result deleteById(@PathVariable String userId){
        log.info("删除用户...");
        userService.deleteById(userId);
        return Result.success("删除成功");
    }

    /**
     * 重设用户密码
     * @param userId
     * @return
     */
    @PutMapping("/resetPassword/{userId}")
    public Result resetPassword(@PathVariable String userId){
        log.info("重设当前用户密码：{}",userId);
        userService.resetPassword(userId);
        return Result.ok("密码已重置");
    }

    /**
     * 修改用户状态
     * @param userDTO
     * @return
     */
    @PostMapping("/status")
    public Result status(@RequestBody UserDTO userDTO){
        log.info("修改用户状态...");
        userService.changeStatus(userDTO);
        return Result.ok("账户状态已修改");
    }

    /**
     * 查询用户权限
     * @param userPageDTO
     * @return
     */
    @GetMapping("/role/list")
    public Result roleList(UserPageDTO userPageDTO){
        //查询表中信息
        log.info("分页查询权限");
        PageResult<UserRoleVO> pageResult = userService.pageRule(userPageDTO);
        return Result.success(pageResult);
    }

    @PostMapping("/role/status")
    public Result changeRoleStatus(@RequestBody UserRoleDTO userRoleDTO){
        log.info("启用/停用权限");
        userService.changeRoleStatus(userRoleDTO);
        return Result.success();
    }

    /**
     * 发送邮箱验证码
     * @param userEmailDTO
     * @return
     */
    @PostMapping("/getEmailCode")
    public Result getEmailCode(@RequestBody UserEmailDTO userEmailDTO){
        log.info("邮箱为：{}",userEmailDTO.getEmail());
        //验证邮箱是否正确
        boolean b = userService.checkEmail(userEmailDTO);
        if(b){
            userService.sendCode(userEmailDTO.getEmail());
            return Result.success();
        }else{
            throw new BusinessException("当前账户信息不存在");
        }

    }

    /**
     * 校验邮箱验证码
     * @param userEmailDTO
     * @return
     */
    @PostMapping("/checkEmailCode")
    public Result checkEmailCode(@RequestBody UserEmailDTO userEmailDTO){
        boolean b = userService.checkCode(userEmailDTO);
        if(b){
            userService.setPasswordByEmail(userEmailDTO);
            return Result.success();
        }else{
            return Result.error("验证码错误，请重试");
        }
    }
}
